#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import json
import os
from hashlib import md5

token=""


def getToken():
    global token
    parms = {
        "grant_type": "client_credentials",
        "client_id": "kML6wjky9NBnnIBdFwt1TMQM",
        "client_secret": "innOGjKz5Tk9vt4dGbEAk4fQG8QbfkRG"
    }
    url_token = "https://openapi.baidu.com/oauth/2.0/token"
    res = requests.get(url_token, params=parms)
    if res.status_code == 200:
        result = res.text
        print(result)
        token=json.loads(result).get("access_token")
        print(token)
    else:
        print(res.text)

if token=="":
    getToken()



def getTts(str):
    print("token:",token)
    parms={
        "cuid":"ssss232323",#唯一标识符
        "ctp":"1",#客户端
        "tex":str,
        "tok":token,
        "lan":"zh",
        "spd":"6", #语调
        "vol":"15", #音量
        "per":"0",#声音类型
         "aue":"6",#返回音频格式
    }
    text2audio_url="https://tsn.baidu.com/text2audio"
    res=requests.get(text2audio_url,params=parms)
    if res.status_code==200:
        save_audio(res.content,str)
        # print(res.text)
    else:
        print(str+"合成失败");

def save_audio(content,str):
    file_path = '{0}/{1}.{2}'.format(os.getcwd(), md5(str.encode("utf-8")).hexdigest(), 'wav')
    print(file_path)
    if not os.path.exists(file_path):
        with open(file_path, 'wb') as f:
            f.write(content)
            f.close()

with open("text",encoding="utf-8") as f:
    for line in f.readlines():
        getTts(line.strip())

# getTts("网络好像有点问题,请稍后重试")
